package com.example.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.mapper.SysUserMapper;
import com.example.demo.pojo.LoginUser;
import com.example.demo.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private SysUserMapper sysUserMapper;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("login_name",username);

    SysUser sysUser = sysUserMapper.selectOne(queryWrapper);

    if (Objects.isNull(sysUser)){
      throw new UsernameNotFoundException("用户名不存在");
    }

    // 查询权限信息
    List<String> perms = sysUserMapper.selectPermsByUserid(sysUser.getUserId());

    LoginUser loginUser = new LoginUser(sysUser,perms);

    return loginUser;
  }
}